from datetime import datetime
from app import db


class LightRecord(db.Model):
    """爆灯记录模型"""
    __tablename__ = 'light_records'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, comment='爆灯用户ID')
    target_user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, comment='目标用户ID')
    matchmaker_id = db.Column(db.Integer, db.ForeignKey('matchmakers.id', ondelete='SET NULL'), comment='推荐红娘ID')
    amount = db.Column(db.Numeric(10, 2), default=10.00, comment='支付金额')
    commission_amount = db.Column(db.Numeric(10, 2), default=3.00, comment='佣金金额')
    commission_rate = db.Column(db.Numeric(5, 2), default=30.00, comment='佣金比例')
    payment_status = db.Column(db.Integer, default=1, comment='支付状态：1待支付2已支付3已退款')
    payment_method = db.Column(db.String(50), comment='支付方式')
    payment_time = db.Column(db.DateTime, comment='支付时间')
    is_notified = db.Column(db.Boolean, default=False, comment='是否已通知')
    notification_time = db.Column(db.DateTime, comment='通知时间')
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')

    # 索引
    __table_args__ = (
        db.Index('idx_user_id', 'user_id'),
        db.Index('idx_target_user_id', 'target_user_id'),
        db.Index('idx_matchmaker_id', 'matchmaker_id'),
        db.Index('idx_payment_status', 'payment_status'),
        db.Index('idx_created_at', 'created_at'),
    )

    def __repr__(self):
        return f'<LightRecord {self.id}>'

    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'target_user_id': self.target_user_id,
            'matchmaker_id': self.matchmaker_id,
            'amount': float(self.amount) if self.amount else 10.00,
            'commission_amount': float(self.commission_amount) if self.commission_amount else 3.00,
            'commission_rate': float(self.commission_rate) if self.commission_rate else 30.00,
            'payment_status': self.payment_status,
            'payment_status_text': self._get_payment_status_text(),
            'payment_method': self.payment_method,
            'payment_time': self.payment_time.strftime('%Y-%m-%d %H:%M:%S') if self.payment_time else None,
            'is_notified': self.is_notified,
            'notification_time': self.notification_time.strftime('%Y-%m-%d %H:%M:%S') if self.notification_time else None,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None
        }
    
    def _get_payment_status_text(self):
        """获取支付状态文本"""
        status_map = {
            1: '待支付',
            2: '已支付',
            3: '已退款'
        }
        return status_map.get(self.payment_status, '未知') 